<script>
import { mapGetters, mapState } from 'vuex'
import addOrEditForm from '@/views/vehicle/vehicleList/components/addOrEditForm/addOrEditForm.vue'
import vehicleList from '@/mixin/vehicleList'
import VehicleInfo from '@/views/vehicle/vehicleList/components/vehicleInfo/vehicleInfo.vue'

export default {
  name: 'vehicleList',
  mixins: [vehicleList],
  components: { VehicleInfo, addOrEditForm },
  data() {
    return {
      /* pageParams: {
         page: 1,
         pageSize: 10,
         truckTypeId: undefined,
         licensePlate: undefined,
         workStatus: undefined
       },*/
      /* 是否显示新增车辆的对话框 */
      addOrEditDialogVisible: false,
      edit: false,
      /* 是否显示配置司机的抽屉组件 */
      drawer: false,
      /* 当前车辆的信息 */
      vehicleInfo: {},
      /* 绑定司机的ID列表 */
      driverIds: [],
      /* 车辆的ID */
      truckId: ''
      // loading: false
      /*
      司机列表
      driverList: [],
      */
    }
  },
  methods: {
    /*
    *获取车辆分页数据的回调函数
    *
    async fetchVehicleList() {
      try {
        this.loading = true
        await this.$store.dispatch('vehicleListStore/fetchVehicleListAction', this.pageParams)
      } catch (error) {
        this.$message.error(error.message)
      } finally {
        this.loading = false
      }
    },
    */

    /*
    *获取车辆类型信息列表的回调函数
    *  */
    async fetchCarModelsListType() {
      try {
        await this.$store.dispatch('carModelsStore/fetchCarModelsListTypeAction')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /*
    * pageSize变化的回调
    *  */
    handleSizeChange(pageSize) {
      this.pageParams.pageSize = pageSize
      this.fetchVehicleList()

    },
    /*
    * page变化的回调
    *  */
    handleCurrentChange(page) {
      this.pageParams.page = page
      this.fetchVehicleList()
    },
    /*
    * 统计车辆停用和可用的回调函数
    *  */
    async getVehicleListCount() {
      try {
        await this.$store.dispatch('vehicleListStore/getVehicleListCountAction')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /*
    * 搜索按钮的回调函数
    *  */
    handleSearch() {
      this.pageParams.page = 1
      this.fetchVehicleList()
    },
    /*
    * 点击重置按钮的回调函数
    *  */
    handleReset() {
      this.pageParams.page = 1
      this.fetchVehicleList()
    },
    /*
    * 点击删除按钮的回调函数
    *  */
    async handleDelete(row) {
      const confirm = await this.$confirm('此操作将永久删除该车辆, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (confirm === 'cancel') return
      try {
        const deleteResult = await this.$store.dispatch('vehicleListStore/deleteVehicleAction', row.id)
        await this.fetchVehicleList()
        this.$message.success(deleteResult)
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /*
    * 点击确认添加车辆或者编辑车辆的回调
    *  */
    async handleSubmit() {
      const validate = await this.$refs.addFormRef.$refs.formRef.validate().catch(error => error)
      if (!validate) return
      if (this.edit) {
        try {
          const editResult = await this.$store.dispatch('vehicleListStore/editVehicleAction', this.$refs.addFormRef.formData)
          this.addOrEditDialogVisible = false
          await this.fetchVehicleList()
          this.$message.success(editResult)
        } catch (error) {
          this.$message.error(error.message)
        }
      } else {
        try {
          const addResult = await this.$store.dispatch('vehicleListStore/addVehicleAction', this.$refs.addFormRef.formData)
          this.addOrEditDialogVisible = false
          await this.fetchVehicleList()
          this.$message.success(addResult)
        } catch (error) {
          this.$message.error(error.message)
        }
      }
    },

    /*
    * 获取所有司机的回调函数
    *  */
    async fetchDriverAll() {
      try {
        await this.$store.dispatch('vehicleListStore/fetchDriverAllAction')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /*
    *
    * 获取车辆所绑定的司机回调函数
    *  */
    async fetchDriverById(truckId) {
      try {
        await this.$store.dispatch('vehicleListStore/fetchDriverByIdAction', truckId)
      } catch (error) {
        this.$message.error(error.message)
      }
    },

    /*
    *
    * 配置司机的回调函数
    *  */
    async handleAssignedDriver(row) {
      const confirm = await this.$confirm('配司机需满足条件:1车辆信息完善 2车辆无未完成任务', '配置司机', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
      if (confirm === 'cancel') return
      await this.fetchDriverAll()
      await this.fetchDriverById(row.id)
      this.drawer = true
      this.vehicleInfo = { ...row }
      this.truckId = row.id
    },

    /*
    *
    * 删除绑定司机的回调函数
    *  */
    deleteBindDriver(id) {
      this.$store.commit('vehicleListStore/deleteDriverMutation', id)
    },

    /*
    *
    * 确认绑定司机的回调函数
    *  */
    async bindDriverSubmit() {
      try {
        const bindInfo = { driverIds: this.bindDriverList.map(item => item.userId), truckId: this.truckId }
        const bindResult = await this.$store.dispatch('vehicleListStore/bindDriverAction', bindInfo)
        this.drawer = false
        this.$message.success(bindResult)
        this.$store.commit('vehicleListStore/clearDriverMutation')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /*
    * 抽屉组件关闭的回调
    *  */
    closeDrawer() {
      this.$store.commit('vehicleListStore/clearDriverMutation')
      this.driverIds = []
    },
    /*
    * 启用或者停用车辆
    *  */
    async startOrEnd({ workStatus, id }) {
      if (workStatus === 0) {
        try {
          const result = await this.$store.dispatch('vehicleListStore/startVehicleAction', id)
          await this.fetchVehicleList()
          this.$message.success(result)
        } catch (error) {
          this.$message.error(error.message)
        }
      } else {
        try {
          const result = await this.$store.dispatch('vehicleListStore/endVehicleAction', id)
          await this.fetchVehicleList()
          this.$message.success(result)
        } catch (error) {
          this.$message.error(error.message)
        }
      }
    },

    /*
    * 点击新增车辆的回调函数
    *  */
    handleAdd() {
      this.edit = false
      this.addOrEditDialogVisible = true
    },

    /*
    *
    * 编辑车辆的回调函数
    *  */
    async handleEdit(row) {
      this.edit = true
      this.addOrEditDialogVisible = true
      this.$nextTick(() => {
        this.$refs.addFormRef.fetchVehicleDetail(row.id)
      })
    },

    changeActive(event) {
      const { type } = event.target.dataset
      if (type === undefined) {
        this.pageParams.workStatus = undefined
      } else if (type === '1') {
        this.pageParams.workStatus = Number(type)
      } else if (type === '0') {
        this.pageParams.workStatus = Number(type)
      }
      this.pageParams.page = 1
      this.fetchVehicleList()
    }
  },
  computed: {
    ...mapState('vehicleListStore', ['bindDriverList', 'driverAllList']),
    ...mapState('carModelsStore', ['carModelsListType']),
    totalCounts() {
      return (Number(this.count[0])) + (Number(this.count[1]))
    },
    title() {
      return this.edit ? '编辑车辆' : '新增车辆'
    }
  }
  ,
  mounted() {
    // this.fetchVehicleList()
    this.getVehicleListCount()
    this.fetchCarModelsListType()
  },
  watch: {
    driverIds(newValue, oleValue) {
      this.$store.commit('vehicleListStore/pushDriverMutation', newValue[newValue.length - 1])
    }
  }
}
</script>

<template>
  <div class="vehicle-list">
    <el-card shadow="never" class="top">
      <el-form inline :model="pageParams">
        <el-form-item label="车辆类型:">
          <el-select v-model="pageParams.truckTypeId">
            <el-option v-for="(item) in carModelsListType" :value="item.id" :label="item.name" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车牌号码:">
          <el-input placeholder="请输入车牌号码" v-model="pageParams.licensePlate"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="never" class="center">
      <ul @click="changeActive">
        <li :class="pageParams.workStatus===undefined?'active':null" :data-type="undefined">全部({{ totalCounts || '999+' }})</li>
        <li :class="pageParams.workStatus===1?'active':null" :data-type="1">可用({{ count[1] || '999+' }})</li>
        <li :class="pageParams.workStatus===0?'active':null" :data-type="0">停用({{ count[0] || '999+' }})</li>
      </ul>
    </el-card>
    <el-card shadow="never" class="bottom">
      <div class="header">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增车辆</el-button>
      </div>
      <el-table :data="vehicleList" border stripe :header-cell-style="{background:'#f4f6f8',color:'#969393'}" v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(255,255,255)">
        <el-table-column type="index" label="序号" align="center" width="80px"></el-table-column>
        <el-table-column prop="driverNum" label="车辆图片" align="center" width="100px">
          <template #default="{row}">
            <el-avatar :size="45" src="https://yjy-teach-oss.oss-cn-beijing.aliyuncs.com/slwl/0aefd0d6-2553-4038-a466-7b2618526046.jpg">
              <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="licensePlate" label="车牌号码" align="center" width="120px"></el-table-column>
        <el-table-column prop="truckTypeName" label="车辆类型" align="center"></el-table-column>
        <el-table-column prop="driverNum" label="司机数量" align="center" width="80px"></el-table-column>
        <el-table-column label="车辆状态" align="center" width="80px">
          <template #default="{row}">
            <el-button type="text">{{ row.workStatus === 0 ? '停用' : '启用' }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="deviceGpsId" label="GBS设备ID" align="center" width="120px"></el-table-column>
        <el-table-column prop="allowableLoad" label="实载重量(T)" align="center" width="120px"></el-table-column>
        <el-table-column prop="allowableVolume" label="实载数量(方)" align="center" width="120px"></el-table-column>
        <el-table-column label="操作" align="center" width="250px">
          <template #default="{row}">
            <el-button type="text" @click="handleAssignedDriver(row)">分配司机</el-button>
            <el-button type="text" @click="$router.push({
            path:'/vehicle-detail',
            query:{
              id:row.id,
            }
            })"
            >详情
            </el-button>
            <el-button type="text" @click="startOrEnd(row)">{{ row.workStatus === 0 ? '启用' : '停用' }}</el-button>
            <el-button type="text" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageParams.page" :page-sizes="[2, 3, 4, 10]" :page-size="pageParams.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="counts" background></el-pagination>
    </el-card>
    <el-dialog :title="title" :visible.sync="addOrEditDialogVisible" :close-on-click-modal="false" @close="$refs.addFormRef.resetFormData()">
      <addOrEditForm ref="addFormRef" :edit="edit"></addOrEditForm>
      <template #footer>
        <el-button @click="addOrEditDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </template>
    </el-dialog>

    <el-drawer title="配置司机" :visible.sync="drawer" @close="closeDrawer">
      <el-scrollbar class="scrollbar">
        <vehicle-info :vehicleInfo="vehicleInfo"></vehicle-info>
        <el-form label-width="80px" inline>
          <el-form-item label="配置司机">
            <el-select collapse-tags multiple placeholder="请选择需要配置的司机" v-model="driverIds">
              <el-option v-for="(item) in driverAllList" :value="item.id" :label="item.account" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-table size="small" border stripe :header-cell-style="{background:'#f4f6f8',color:'#969393'}" :data="bindDriverList">
          <el-table-column type="index" label="序号" width="50px" align="center"></el-table-column>
          <el-table-column prop="account" label="司机账号" align="center"></el-table-column>
          <el-table-column prop="name" label="司机名称" align="center"></el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="{row}">
              <el-button type="text">查看</el-button>
              <el-button type="text" @click="deleteBindDriver(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="btn-box">
          <el-button>取消</el-button>
          <el-button type="primary" @click="bindDriverSubmit">确认</el-button>
        </div>
      </el-scrollbar>
    </el-drawer>
  </div>
</template>

<style scoped lang="scss">
.vehicle-list {
  padding: 20px;

  .top {
    .el-form {
      .el-form-item {
        width: 350px;
      }

      .el-input {
        width: 130% !important;
      }

      .el-select {
        width: 130% !important;
      }
    }
  }

  .center {
    margin: 20px 0;

    ::v-deep .el-card__body {
      padding: 0 !important;
      height: 50px;
    }

    ul {
      display: flex;

      li {
        height: 100%;
        line-height: 50px;
        text-align: center;
        width: 120px;
        font-size: 15px;
        font-weight: 520;
        color: #333333;
        cursor: pointer;

        &:hover {
          color: #e15536;
        }

        &.active {
          background-color: #ffeeeb;
          color: #e15536;
        }
      }
    }
  }

  .bottom {
    .el-table {
      margin: 10px 0;
    }

    .el-pagination {
      display: flex;
      justify-content: center;
    }
  }

  ::v-deep .el-drawer__body {
    padding: 10px !important;
  }

  ::v-deep .el-drawer__header {
    font-size: 17px;
    font-weight: 600;
    background-color: #f3f4f7;
    padding: 10px;
  }

  .el-select {
    width: 250px;
  }

  .scrollbar {
    height: 600px;

    .btn-box {
      display: flex;
      justify-content: center;
      margin: 10px 0;
    }
  }

}
</style>
